package com.ty.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * jwt工具
 *
 * @author Mjg @QQ:2091864671 @Creates by mjg ON 2020/6/25-11:06
 * @date 2020/06/25
 */
@Slf4j
@Component
public class JwtUtils {

  /** 密钥 */
  private static final String KEY = "sass-mjg";
  /** 过期时间 */
  private static final Long TTL = 60 * 60 * 1000L;

  /**
   * 创建jwt 创建jwt 创建jwt token
   *
   * @param id id
   * @param name 的名字
   * @return {@link String}
   */
  public String createJwt(String id, String name) {

    // 获取当前时间
    long now = System.currentTimeMillis();
    // 设置token失效时间
    long exp = now + TTL;

    JwtBuilder jwtBuilder =
        Jwts.builder()
            .setId(id)
            .setSubject(name)
            .setIssuedAt(new Date())
            .signWith(SignatureAlgorithm.HS256, KEY);

    jwtBuilder.setExpiration(new Date(exp));
    return jwtBuilder.compact();
  }

  /**
   * 解析jwt
   *
   * @param token 令牌
   * @return {@link Claims}
   */
  public Claims parseJwt(String token) {
    Claims claims;
    if (token != null) {
      try {
        claims = Jwts.parser().setSigningKey(KEY).parseClaimsJws(token).getBody();
        return claims;
      } catch (ExpiredJwtException e) {
        log.error("Token 已过期");
        throw new RuntimeException("身份认证过期");
      } catch (UnsupportedJwtException e) {
        log.error("Token 验证失败");
        throw new RuntimeException("验证失败");
      } catch (MalformedJwtException | SignatureException | IllegalArgumentException e) {
        log.error("Token 异常");
        throw new RuntimeException("token 异常");
      }
    }
    throw new RuntimeException("程序异常");
  }
}
